# For fileutils.rb, this vulnerability is reported in [ruby-dev:26100].
#
def remove_entry_secure(path, force = false)
unless fu_have_symlink?
remove_entry path, force
return
end
fullpath = File.expand_path(path)
st = File.lstat(fullpath)
unless st.directory?
File.unlink fullpath
return
end
# is a directory.
parent_st = File.stat(File.dirname(fullpath))
unless fu_world_writable?(parent_st)
remove_entry path, force
return
end
unless parent_st.sticky?
raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})"
end
# freeze tree root
euid = Process.euid
File.open(fullpath + '/.') {|f|
unless fu_stat_identical_entry?(st, f.stat)
# symlink (TOC-to-TOU attack?)
File.unlink fullpath
return
end
f.chown euid, -1
f.chmod 0700
}
# ---- tree root is frozen ----
root = Entry_.new(path)
root.preorder_traverse do |ent|
if ent.directory?
ent.chown euid, -1
ent.chmod 0700
end
end
root.postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry_secure
def fu_world_writable?(st)
(st.mode & 0002) != 0
end
private_module_function :fu_world_writable?
def fu_have_symlink? #:nodoc
File.symlink nil, nil
rescue NotImplementedError
return false
rescue
return true
end
private_module_function :fu_have_symlink?
def fu_stat_identical_entry?(a, b) #:nodoc:
a.dev == b.dev and a.ino == b.ino
end
private_module_function :fu_stat_identical_entry?
#
# This method removes a file system entry +path+.
# +path+ might be a regular file, a directory, or something.
# If +path+ is a directory, remove it recursively.
#
# See also #remove_entry_secure.
#
def remove_entry(path, force = false)
Entry_.new(path).postorder_traverse do |ent|
begin
ent.remove
rescue
raise unless force
end
end
rescue
raise unless force
end
module_function :remove_entry
#
# Removes a file +path+.
# This method ignores StandardError if +force+ is true.
#
def remove_file(path, force = false)
Entry_.new(path).remove_file
rescue
raise unless force
end
module_function :remove_file
#
# Removes a directory +dir+ and its contents recursively.
# This method ignores StandardError if +force+ is true.
#
def remove_dir(path, force = false)
remove_entry path, force # FIXME?? check if it is a directory
end
module_function :remove_dir
#
# Returns true if the contents of a file A and a file B are identical.